package com.yusong.open.sdk.utils;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.SocketTimeoutException;

/**
 * Created by yusong on 2018/7/10.
 * OK HTTP日志记录
 */
public class HttpLogInterceptor implements Interceptor {

    private static final Logger logger = LoggerFactory.getLogger(HttpLogInterceptor.class);

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        String url = request.url().toString();
        String method = request.method();

        long t1 = System.nanoTime();
        long start = System.currentTimeMillis(),finish= System.currentTimeMillis();
        logger.info(String.format("HttpLogInterceptor|Sending request %s on %s%n%s",
                request.url(), chain.connection(), request.headers()));

        
        int statusCode =-1;
        Response response = null;
        try{
        	//执行请求
        	response = chain.proceed(request);
        	
            long t2 = System.nanoTime();
            logger.info(String.format("HttpLogInterceptor|Received response for %s in %.1fms%n%s",
                    response.request().url(), (t2 - t1) / 1e6d, response.headers()));
            
            statusCode = response.code();
            finish = System.currentTimeMillis();
            logger.info("HTTPRPC|url:{}|method:{}|statusCode:{}|excutetime:{}",url,method,statusCode,finish-start);
        }catch(IOException e){
        	if(e instanceof SocketTimeoutException){
        		statusCode = 408;
        		finish = System.currentTimeMillis();
        		logger.info("HTTPRPC|url:{}|method:{}|statusCode:{}|excutetime:{}",url,method,statusCode,finish-start);
        	}
        	//统计完成以继续抛出异常
        	e.printStackTrace();
        	throw e;
        }
        return response;
    }
}
